package cn.xinfei.xdecision.manager.controller.data;


import cn.xinfei.xdecision.common.model.common.ResponseEntityBuilder;
import cn.xinfei.xdecision.common.model.common.ResponseEntityDto;
import cn.xinfei.xdecision.common.model.common.VarPageResult;
import cn.xinfei.xdecision.common.model.common.requestParam.UpdateFolderParam;
import cn.xinfei.xdecision.common.model.datax.datamanage.v2.Variable;
import cn.xinfei.xdecision.common.model.datax.datamanage.v2.resp.VariableResp;
import cn.xinfei.xdecision.common.model.datax.datamanage.v2.vo.VariableRespVO;
import cn.xinfei.xdecision.common.model.login.SSOUser;
import cn.xinfei.xdecision.common.model.login.SessionManager;
import cn.xinfei.xdecision.common.service.datax.datamanage.v2.VariableService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @apiDefine datamanage 变量管理
 */
@Controller
@RequestMapping("datamanage/variable")
@ResponseBody
public class VariableController {

    @Autowired
    private VariableService variableService;


    /**
     *  获取变量列表
   */
    //used
    @ApiOperation(value = "获取变量列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResponseEntityDto<Object> list(@RequestBody HashMap<String, Object> paramMap) {


        SSOUser loginAccount = SessionManager.getLoginAccount();
        paramMap.put("userId", loginAccount.getId());
        paramMap.put("organId", loginAccount.getOrganId());
        String searchKey = (String) paramMap.get("searchKey");

        ResponseEntityDto<VarPageResult<List<VariableRespVO>, Variable>> varPageResult = variableService.findByVarType(paramMap);
        HashMap<String, Object> modelMap = new HashMap<>();
        modelMap.put("pager", varPageResult.getData().getPageInfo());
        modelMap.put("klist", varPageResult.getData().getKlist());
        modelMap.put("searchKey", searchKey);

        return ResponseEntityBuilder.buildNormalResponse(modelMap);
    }


    /**
     *  获当前用户的所有变量
     */
    @ApiOperation(value = "获当前用户的所有变量")
    @RequestMapping(value = "/findVariableByUser", method = RequestMethod.POST)
    public ResponseEntityDto<Object> findVariableByUser(@RequestBody HashMap<String, Object> paramMap) {

        Long userId = SessionManager.getLoginAccount().getId();
        Long organId = SessionManager.getLoginAccount().getOrganId();
        paramMap.put("userId", userId);
        paramMap.put("organId", organId);

        Integer isCommon = 1;
        paramMap.put("isCommon", isCommon);

        if (!paramMap.containsKey("varCodes")) {
            paramMap.put("varCodes", null);
        }
        List<VariableResp> varRespList = variableService.findByUser(paramMap).stream()
                .map(var -> {
                    VariableResp variableResp = new VariableResp();
                    variableResp.setVarCode(var.getVarCode());
                    variableResp.setDefaultValue(var.getVarDefaultValue());
                    variableResp.setVarName(var.getVarName());
                    variableResp.setValueType(String.valueOf(var.getVarValueType()));
                    variableResp.setVarType(String.valueOf(var.getVarType()));
                    return variableResp;
                }).collect(Collectors.toList());
        paramMap.put("varCodeList", varRespList);

        return ResponseEntityBuilder.buildNormalResponse(paramMap);
    }


    /**
     * @api {POST} /v2/datamanage/datamanage/downTemplate 2.10. 变量导入模板下载
     * @apiGroup datamanage
     * @apiVersion 2.0.0
     */
    @ApiOperation(value = "变量导入模板下载")
    @RequestMapping("downTemplate")
    public ResponseEntity<byte[]> downExcelTemplate() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("excleTemplate/datamanage.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        HttpHeaders headers = new HttpHeaders();
        String fileName = new String("基础变量导入模板.xlsx".getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(IOUtils.toByteArray(inputStream), headers, HttpStatus.CREATED);
    }

    /**
     * @api {POST} /v2/datamanage/datamanage/upload 2.11. 批量导入变量
     * @apiGroup datamanage
     * @apiVersion 2.0.0
     */
    @ApiOperation(value = "批量导入变量")
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public ResponseEntityDto<Object> upload(HttpServletRequest request) throws Exception {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"

        String accessUrl = "";
        String fileName = "";
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {

                    String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/fieldUpload/";
                    if (!new File(uploadDir).exists()) {
                        File dir = new File(uploadDir);
                        dir.mkdirs();
                    }
                    fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                    String path = uploadDir + fileName;
                    //上传
                    file.transferTo(new File(path));
                    accessUrl = path;
                }
            }
        }

        Long userId = SessionManager.getLoginAccount().getId();
        Long organId = SessionManager.getLoginAccount().getOrganId();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId);
        paramMap.put("organId", organId);
        Integer isCommon = 0;
        if (paramMap.get("engineId") == null) {
            isCommon = 1;
        } else {
            isCommon = 0;
        }
        paramMap.put("isCommon", isCommon);

        Map<String, Object> resultMap = variableService.importExcel(accessUrl, paramMap);
        return ResponseEntityBuilder.buildNormalResponse(resultMap);
    }


    @PostMapping(value = "/updateFieldFolder")
    public ResponseEntityDto<Object> updateFieldFolder(@RequestBody UpdateFolderParam param) {
        UpdateFolderParam.checkNotNull(param);
        int result = variableService.updateVariableFolder(param);
        if (result > 0) {
            return ResponseEntityBuilder.buildNormalResponse("成功移动" + result + "条数据");
        }
        return ResponseEntityBuilder.buildErrorResponse("移动失败", "");
    }


}
